package net.fukure.android.pecabc.service;

import net.fukure.android.pecabc.media.Encoder;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class BackgroundService extends Service {

	final static String LOG_TAG = "AndroidFFWMEMMService";

	private final IBinder mBinder = new MMServiceLocalBinder();
	private MMServer server = null;
	private Encoder recoder = null;
	//private Watcher watcher = null;
	private Notification notification = null;
	private boolean broadcast = false;
	
	public class MMServiceLocalBinder extends Binder {
		BackgroundService getService() {
			return BackgroundService.this;
		}
	}
	 
	@Override
	public IBinder onBind(Intent intent) {
		Log.i(LOG_TAG, "onBind" + ": " + intent);
		return mBinder;
	}
	 
	@Override
	public void onRebind(Intent intent){
		Log.i(LOG_TAG, "onRebind" + ": " + intent);
	}
	 
	@Override
	public boolean onUnbind(Intent intent){
		Log.i(LOG_TAG, "onUnbind" + ": " + intent);
		return true;
	}
	/*
	class Watcher extends Thread {
		private boolean run = true;
		@Override
		public void run() {
			super.run();
			try {
				while(run){
					Log.d(LOG_TAG, "notification");
					Thread.sleep(10000);
					if(recoder.isRecording()){
						Log.d(LOG_TAG, "notification");
						notification.show(1);
					}
				}
			} catch (InterruptedException e) {
				//e.printStackTrace();
			}
		}
		public void end(){
			run = false;
			interrupt();
		}
	}
	*/
	@Override
	public void onCreate() {
		super.onCreate();
		
		Log.d(LOG_TAG, "onCreate");

		notification = new Notification(this);
		
		if(server==null){
			server = new MMServer();
			server.start();
		}
		
		if(recoder==null){
			recoder = new Encoder(this);
		}
		
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		Log.d(LOG_TAG, "onStartCommand");
		
		return START_STICKY;
	}
	  
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		Log.d(LOG_TAG, "onDestroy");

		if(server!=null){
			server.kill();
			server = null;
		}
		
		if(recoder!=null){
			if(recoder.isRecording()){
				recoder.stopRec();
			}
			recoder.release();
		}
		
		/*
		if(watcher!=null){
			watcher.end();
		}
		*/
	}
	
	public void startForeground(){
		Log.d(LOG_TAG, "startForeground");
		notification.show(1);
		/*
		if(watcher!=null){
			watcher.end();
		}
		watcher = new Watcher();
		watcher.start();
		*/
	}
	
	public void stopForeground(){
		Log.d(LOG_TAG, "stopForeground");
		notification.hide();
		//watcher.end();
	}
	
	public boolean isBroadcast() {
		return broadcast;
	}
	
	public void setBroadcast(boolean broadcast){
		this.broadcast = broadcast;
	}
	
	public Encoder getEncoder(){
		return recoder;
	}
	
	public MMServer getServer(){
		return server;
	}

}